<%@ page import="com.deepai.dprsmgr.utils.ErrCode" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@include file="../base_path.jsp" %>


<div class="modal-header">
	<button id="btn_close" type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
	<h4 class="modal-title">创建业务</h4>
</div>
<div class="modal-body">

	<div class="container-fluid container-fluid-w" style="width: 90%;margin-top: 20px;">
		<form id="form_business_create" class="form-horizontal" style="padding: 20px">
			<div class="form-group">
				<label class="col-xs-3 control-label">
					<label class="text-danger" style="margin-right: 5px">*</label>业务名称</label>
				<div class="col-xs-8">
					<input type="text" class="form-control input-sm" id="txt_business_name" name="txt_business_name" placeholder="只支持中文、字母、数字、下划线，且不能以下划线开头或结尾"
					 maxlength="60">
					<span id="help_business_name" class="help-block"></span>
				</div>
			</div>
			<div class="form-group">
				<label class="col-xs-3 control-label">业务描述</label>
				<div class="col-xs-8">
					<textarea class="form-control input-sm" id="textarea_business_comment" name="textarea_business_comment"
					 placeholder="只支持中文、字母、数字，下划线、逗号、句号，最多输入80个字..." maxlength="80"></textarea>
					<span id="help_textarea_business_comment" class="help-block"></span>
				</div>
			</div>

			<div class="form-group">
				<label class="col-xs-3 control-label">
					<label class="text-danger" style="margin-right: 5px">*</label>所属组织</label>
				<div class="col-md-8">
					<shiro:hasAnyRoles name="role_super_admin,role_admin">
						<select id="txt_org" class="selectpicker form-control input-sm" name="txt_org" data-live-search="true" title="请选择"
						 data-live-search-placeholder="Search" data-actions-box="true">
							<option value="${defaultOrg.id}" selected>${defaultOrg.orgName}</option>
							<c:if test="${not empty orgList && orgList.size() > 0}">
								<c:forEach var="item" items="${orgList}">
									<c:choose>
										<c:when test="${item.status == 1}">
											<option value="${item.id}">${item.orgName}</option>
										</c:when>
										<c:otherwise></c:otherwise>
									</c:choose>
								</c:forEach>
							</c:if>
						</select>
					</shiro:hasAnyRoles>
					<shiro:hasAnyRoles name="dep_leader,quality_specialist,analysis_specialist,call_specialist">
						<select id="txt_org" class="selectpicker form-control input-sm" name="txt_org" disabled data-actions-box="true">
							<option value="${defaultOrg.id}" selected>${defaultOrg.orgName}</option>
							<c:forEach var="item" items="${orgList}">
								<option value="${item.id}">${item.orgName}</option>
							</c:forEach>
						</select>
					</shiro:hasAnyRoles>
				</div>
			</div>
			<div class="form-group">
				<label class="col-xs-3 control-label">
					<label class="text-danger" style="margin-right: 5px">*</label>业务模板</label>
				<div class="col-xs-8">
					<select id="select_business_template" class="selectpicker form-control input-sm" data-live-search="true" title="请选择"
					 name="select_business_template" data-live-search-placeholder="Search" data-actions-box="true">
					</select>
				</div>
			</div>

			<div class="form-group hidden">
				<label class="col-xs-3 control-label">
					<label class="text-danger" style="margin-right: 5px">*</label>黑名单校验</label>
				<div class="col-xs-8">
					<input type="checkbox" data-size="small" id="switch_blacklist_check">
				</div>
			</div>
			<div class="form-group" id="blacklist_group">
				<div class="col-xs-8 col-xs-offset-3">
					<select id="select_blacklist" class="selectpicker form-control input-sm" multiple data-live-search="true"
					 data-live-search-placeholder="Search" data-actions-box="true" disabled>

					</select>
				</div>
			</div>
			<div class="form-group text-c">

				<button type="submit" class="btn btn-primary btn-sm btn-s">提交</button>

			</div>
		</form>
	</div>


</div>

<%--<script type="text/javascript" src="<%=basePath%>/lib/jquery/3.2.1/jquery.min.js"></script>--%>
<%--<script type="text/javascript" src="<%=basePath%>/lib/bootstrap/3.3.7/js/bootstrap.js"></script>--%>
<%--<script type="text/javascript" src="<%=basePath%>/lib/bootstrap-switch/js/bootstrap-switch.min.js"></script>--%>
<%--<script type="text/javascript" src="<%=basePath%>/lib/bootstrap-select/js/bootstrap-select.min.js"></script>--%>
<%--<script type="text/javascript" src="<%=basePath%>/lib/bootstrap-select/js/i18n/defaults-zh_CN.js"></script>--%>
<%--<script type="text/javascript" src="<%=basePath%>/lib/jquery.validation/1.14.0/jquery.validate_1.js"></script>--%>
<%--<script type="text/javascript" src="<%=basePath%>/lib/jquery.validation/1.14.0/validate-methods.js"></script>--%>
<%--<script type="text/javascript" src="<%=basePath%>/lib/lobibox/js/lobibox.min.js"></script>--%>
<%--<script type="text/javascript" src="<%=basePath%>/lib/lobibox/js/messageboxes.min.js"></script>--%>
<%--<script type="text/javascript" src="<%=basePath%>/lib/lobibox/js/notifications.min.js"></script>--%>
<%--<script type="text/javascript" src="<%=basePath%>/js/common.js"></script>--%>


<script type="text/javascript">
	var checkNameUrl, $businessName, $businessComment, $selectOrg, $selectBusinessTemplate, $blacklistCheck,
		$selectBlacklists;
	var firstOrgFalg = false,
		firstBlackFalg = false;
	$(function() {
		// 对象及变量声明
		checkNameUrl = "<%=basePath%>/business/checkBusinessNameUniqueness.do";
		$businessName = $("#txt_business_name");
		$businessComment = $("#textarea_business_comment");
		$selectOrg = $("#txt_org");
		$selectBusinessTemplate = $("#select_business_template");
		$blacklistCheck = $("#switch_blacklist_check");
		$selectBlacklists = $("#select_blacklist");
		checkBlacklist = false;
		// 初始化开关
		$blacklistCheck.bootstrapSwitch({
			onText: "开启",
			offText: "关闭",
			onColor: "success",
			offColor: "danger",
			size: "small",
			onSwitchChange: function(event, state) {
				if (state == true) {
					$(this).val("1");
					checkBlacklist = true;
					$selectBlacklists.prop("disabled", false);
					$selectBlacklists.selectpicker('refresh');
					$('#blacklist_group').removeClass('hidden');
				} else {
					$(this).val("0");
					checkBlacklist = false;
					$selectBlacklists.prop("disabled", true);
					$selectBlacklists.selectpicker('refresh');
					$selectBlacklists.selectpicker('deselectAll');
					$('#blacklist_group').addClass('hidden');
				}
			}
		});
		$blacklistCheck.bootstrapSwitch('state', false);
		$selectBlacklists.selectpicker();
		$('#blacklist_group').addClass('hidden');
		$('#txt_org').selectpicker();
		$('#select_business_template').selectpicker();
		txt_myorg_cbs();
		$("#form_business_create").validate({
			errorPlacement: function(error, element) {
				// Append error within linked label
				//console.log(element)
				$(element)
					.closest("div.form-group")
					.find("span.help-block")
					.append(error);
			},
			errorElement: "p",
			rules: {
				txt_business_name: {
					required: true,
					isNameChinese: true,
					remote: {
						type: "POST",
						url: checkNameUrl, //请求地址
						data: {
							businessName: function() {
								return $("#txt_business_name").val();
							},
							type: 1
						},
						dataFilter: function(data) {
							if (typeof(data) === "string") {
								data = JSON.parse(data);
							}
							if (data['errorCode'] == "0") {
								return true;
							} else {
								return false;
							}
						}
					}
				},
				textarea_business_comment: {
					commentCheck: true,
				},
				txt_org: {
					required: true
				},
				select_business_template: {
					required: true
				}
			},
			messages: {
				txt_business_name: {
					required: "业务名称不能为空，请重新输入",
					isNameChinese: "字符或格式有误，只支持中文、字母、数字、下划线，且不能以下划线开头或结尾",
					remote: "业务名称已存在，请重新输入"
				},
				textarea_business_comment: {
					commentCheck: "只能包含中文、英文、数字、下划线、逗号、句号"
				},
				txt_org: {
					required: "所属组织不能为空，请选择"
				},
				select_business_template: {
					required: "业务模板不能为空，请选择",
				}
			}
		});
		// 业务名称唯一性实时异步校验


		$selectOrg.on('changed.bs.select', txt_myorg_cbs);
		<shiro:hasAnyRoles name = "role_admin,quality_specialist,analysis_specialist,call_specialist" >
			firstOrgFalg = true;
			firstBlackFalg = true;
			txt_myorg_cbs();
		</shiro:hasAnyRoles>
		$selectBusinessTemplate.add($selectBlacklists).on('show.bs.select', function(e) {
			if (isEmpty($('#txt_org').val())) {
				myNotify("error", "", "请先选择所属组织");
			}
		});

		// 表单提交
		$("#form_business_create").submit(function(event) {
			var businessName = $.trim($businessName.val());
			var businessComment = $.trim($businessComment.val());
			var selectOrgId = $selectOrg.val();
			var businessTemplateId = $selectBusinessTemplate.val();
			var arrBlacklistId = $selectBlacklists.val();

			if (arrBlacklistId.length > 0) {
				checkBlacklist = true;
			}
			if (!regexCheckName(businessName)) {
				myNotify("error", "", "业务名称为字母数字下划线和汉字，且不能以_开头结尾");
				return false;
			}
			if (!$("#form_business_create").valid()) {
				myNotify("warning", "", "请修复错误后在提交！");
				return false;
			}
			if (checkBlacklist && arrBlacklistId.length == 0) {
				myNotify("warning", "", "请选择黑名单或者关闭黑名单校验！");
				return false;
			}
			// 这里用的是this，如果是Form的话需要Form[0]
			var formData = new FormData(this);
			formData.append("businessName", businessName);
			formData.append("businessDesp", businessComment);
			formData.append("orgId", selectOrgId);
			formData.append("templateId", businessTemplateId);
			formData.append("checkBlacklist", checkBlacklist);
			formData.append("blacklistIds", arrBlacklistId);

			// 阻止当前提交事件，自行实现，否则会跳转
			event.preventDefault();
			$.ajax({
				url: '<%=basePath%>/business/createBusiness.do',
				type: 'POST',
				data: formData,
				// 这两个参数需要被定义，否则报错
				contentType: false,
				processData: false,
				traditional: true,
				success: function(data) {
					if (data["errorCode"] === "<%=ErrCode.ERR_CODE_SUCCESS%>") {
						myNotify("success", "", "业务创建成功！");
						$("#modal_create_business").modal("hide");
					} else if (data["errorCode"] === "<%=ErrCode.TASK_ERR_CODE_UNIQUENESS%>") {
						myNotify("error", "", data["msg"]);
					} else {
						myNotify("error", "", "业务创建失败！");
					}
				},
				error: function() {
					myNotify("error",
						"", "业务创建过程中发生错误，请联系管理员！");
				}
			});
			return false;
		});
	});
	/******************************方法声明**********************************/
	// 校验业务名称唯一性
	function checkBusinessNameCorrect($this, name, url) {
		$this.parent().parent().removeClass("has-success");
		$this.parent().parent().removeClass("has-error");
		$this.parent().parent().removeClass("has-feedback");
		$this.nextUntil("#help_business_name").remove();
		if (isEmpty(name) || !regexCheckName(name) || !CheckName(name, true).pass) {
			showBlacklistNameCheckError($this);
			return;
		}

		$.ajax({
			url: url,
			async: 'true',
			dataType: 'json',
			type: 'POST',
			success: function(data) {
				if (data['errorCode'] == "0") {
					showBlacklistNameCheckSuccess($this);
				} else {
					showBlacklistNameCheckError($this);
				}
			}
		});

	}

	function showBlacklistNameCheckSuccess($this) {
		$this.parent().parent().addClass("has-success has-feedback");
		var errHtml = "<span class='glyphicon glyphicon-ok form-control-feedback' aria-hidden='true'>" +
			"</span><span class='sr-only'>(success)</span>";
		$this.after(errHtml);

	}

	function showBlacklistNameCheckError($this) {
		$this.parent().parent().addClass("has-error has-feedback");
		var errHtml = "<span class='glyphicon glyphicon-remove form-control-feedback' aria-hidden='true'></span>" +
			"<span class='sr-only'>(error)</span>";
		$this.after(errHtml);
	}

	function txt_myorg_cbs() {
		var formData = new FormData($("#form_create_account")[0]);
		formData.append("orgId", $("#txt_org").val());
		$.ajax({
			url: '<%=basePath%>/account/getBusinessTemplate.do',
			type: 'POST',
			data: formData,
			async: false,
			// 这两个参数需要被定义，否则报错
			contentType: false,
			processData: false,
			traditional: true,
			success: function(data) {
				$selectBusinessTemplate.empty();
				for (var i = 0; i < data.list.length; ++i) {
					if (i === 0) {
						$selectBusinessTemplate.append("<option value='" + data.list[i].id + "' selected>" + data.list[i].templateCode +
							"</option>")
					} else {
						$selectBusinessTemplate.append("<option value='" + data.list[i].id + "'>" + data.list[i].templateCode +
							"</option>")
					}
				}
				//                $.each(data.list, function (a, b) {
				//                    $selectBusinessTemplate.append("<option value='" + b.id + "'>" + b.templateName + "</option>")
				//                })
				$selectBusinessTemplate.selectpicker('refresh');
				$selectBusinessTemplate.selectpicker('deselectAll');
				if (!firstOrgFalg) {
					$selectBusinessTemplate.blur()
					firstOrgFalg = false;
				}
				$selectBusinessTemplate.selectpicker('refresh');
			},
			error: function() {
				myNotify("error", "", "查询相关模板过程中发生错误，请联系管理员！");
			}
		});


		<%--$.ajax({--%>
			<%--url: '<%=basePath%>/business/getBlacklist.do',--%>
			<%--type: 'POST',--%>
			<%--data: formData,--%>
			<%--async: false,--%>
			<%--// 这两个参数需要被定义，否则报错--%>
			<%--contentType: false,--%>
			<%--processData: false,--%>
			<%--traditional: true,--%>
			<%--success: function(data) {--%>
				<%--console.log(data);--%>
				<%--$selectBlacklists.empty();--%>
				<%--$.each(data.list, function(a, b) {--%>
					<%--$selectBlacklists.append("<option value='" + b.id + "'>" + b.blacklistName + "</option>")--%>
				<%--})--%>
				<%--$selectBlacklists.selectpicker('refresh');--%>
				<%--$selectBlacklists.selectpicker('deselectAll');--%>
				<%--if (!firstBlackFalg) {--%>
					<%--$selectBlacklists.blur()--%>
					<%--firstBlackFalg = false;--%>
				<%--}--%>
				<%--$selectBlacklists.selectpicker('refresh');--%>
			<%--},--%>
			<%--error: function() {--%>
				<%--myNotify("error", "", "查询黑名单发生错误，请联系管理员！");--%>
			<%--}--%>
		<%--});--%>
	}
</script>
